//
//  RMFirstViewController.m
//  rmplanner
//
//  Created by Andrew Pigram on 2/05/12.
//  Copyright (c) 2012 PiAMP Productions. All rights reserved.
//

#import "RMFirstViewController.h"
#import "RMParser.h"
#import "RMMeal.h"
#import "RMTabBarController.h"

@interface RMFirstViewController ()

// place any local message declarations and any globals here
@property (strong, nonatomic) UIAlertView* alertView;
@property (strong, nonatomic) UIActivityIndicatorView* indicator;

@end

static int selectedRow = 0;

@implementation RMFirstViewController

// synthesize
@synthesize meals, mealData, selectedCell, alertView, indicator;

- (void)viewWillAppear:(BOOL)animated
{
	NSURL* url = [[NSURL alloc] initWithScheme:@"http" host:@"rmplanner.net" path:@"/kitchen/scripts/todaysMeals"];
	NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
	NSData* data = [[NSString stringWithFormat:@"user_id=%d", [[NSUserDefaults standardUserDefaults] integerForKey:@"uid"]] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
	[request setHTTPBody:data];
	[request setHTTPMethod:@"POST"];
	NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	NSAssert((connection != nil), @"Failed to create a connection");
	
	//create and display the loading alert
	alertView = [[UIAlertView alloc] init];
	alertView.title = @"Loading";
	alertView.frame = CGRectMake(110, 20, 50, 50);
	indicator = [[UIActivityIndicatorView alloc] init];
	indicator.frame = CGRectMake(120, 45, 40, 40);
	[indicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
	[alertView addSubview:indicator];
	[alertView show];
	[indicator startAnimating];
}

#pragma mark UITableViewController functions
- (void)viewDidLoad
{
    [super viewDidLoad];
	
	self.navigationItem.title = @"Today's Meals";
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

// lock device orientations
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
	    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
	} else {
	    return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight);
	}
}

#pragma mark UITableViewController datasource/delegate functions

// populate each cell with parsed data. Overridden from the UITableViewDataSource protocol
- (UITableViewCell *)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	// create a closed cell
	UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"ClosedCell"];
	if (cell == nil)
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ClosedCell"];
	cell.textLabel.text = ((RMMeal *)[meals objectAtIndex:indexPath.row]).name;
	// Add connection code here
	return cell;
}

// return the number of rows
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
	return [meals count];
}

// if a phone device, use accordion. Else, give data to the detail view controller
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	// for the phone idiom, use the accordion style
	selectedRow = indexPath.row;
	if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
	{
		RMDetailViewController* controller = [[[self splitViewController] viewControllers] objectAtIndex:1];
		[controller setDetailItem:[meals objectAtIndex:indexPath.row] fromController:self];
		selectedCell = indexPath.row;
	}
	else
	{
		[self performSegueWithIdentifier:@"Details" sender:self];
	}
}

#pragma mark Segue functions

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"Details"])
	{
		RMMeal* selectedMeal = [meals objectAtIndex:selectedRow];
		RMDetailViewController* controller = [segue destinationViewController];
		[controller setDetailItem:selectedMeal fromController:self];
		selectedCell = selectedRow;
    }
}

#pragma mark Interface builder actions

- (IBAction)logout
{
	[self dismissModalViewControllerAnimated:YES];
}

#pragma mark NSURLConnection delegate functions

// force use of stored credentials for authentication challenges
- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection
{
	return YES;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	// initialise the data container
	mealData = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	// append the newly downloaded data
	[mealData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	// nullify the connection (to disconnect) and turn off the activity indicator to signify that it is complete
	connection = nil;
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	[alertView dismissWithClickedButtonIndex:0 animated:YES];
	[indicator stopAnimating];
	
	// start parsing the downloaded data
	RMParser* parser = [[RMParser alloc] init];
	[parser setData:mealData sender:self];
	[parser start];
	
	[self.tableView reloadData];
	
	if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
	{
		RMDetailViewController* controller = [[[self splitViewController] viewControllers] objectAtIndex:1];
		controller.meal = [meals objectAtIndex:selectedRow];
		controller.description.text = ((RMMeal *)[meals objectAtIndex:selectedRow]).description;
		controller.mealButton.hidden = !controller.meal.orderable;
		selectedCell = selectedRow;
		
		if ([meals count] > 0)
			[self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:selectedRow inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
	}
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	[alertView dismissWithClickedButtonIndex:0 animated:YES];
	[indicator stopAnimating];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	NSLog(@"%@", [error description]);
	connection = nil;
	UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Connection Error" message:@"Connection to server failed" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[alert show];
}

@end
